package com.example.teadoctor;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Objects;

public class OperateFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.page_operate,container,false);

        // 获取TeaDBHelper对象
        TeaDBHelper dbHelper = new TeaDBHelper(getActivity());

        // 获取SQLiteDatabase对象
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        String query = "SELECT * FROM tea_business";
        Cursor cursor = db.rawQuery(query, null);
        final ArrayList<String> dataList = new ArrayList<>();
        final ArrayList<String> titleList = new ArrayList<>();
        while(cursor.moveToNext()) {
            int business_id = cursor.getInt(cursor.getColumnIndex("business_id"));
            String title = cursor.getString(cursor.getColumnIndex("business_title"));
            String record = business_id + "     " + title ;
            dataList.add(record);
            titleList.add(title);
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(Objects.requireNonNull(getActivity()), android.R.layout.simple_list_item_1, dataList);
        ListView listView = view.findViewById(R.id.Pst_my_operate);
        listView.setAdapter(adapter);
        // 点击记录跳转，要传递数据过去，具体展示
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String selectedRecord = (String) parent.getItemAtPosition(position); // 获取所选中的记录
                // 解析记录中的数据
                String title = titleList.get(position);

                // 将茶名通过intent传递给要跳转的页面
                Intent intent = new Intent(getActivity(), BusinessInformation.class);
                intent.putExtra("title", title);
                startActivity(intent);
            }
        });
        // 关闭结果集和数据库连接
        cursor.close();
        db.close();
        return view;
    }
}
